<template>
  <div class="createPost-container">
    <el-form ref="postForm" v-loading.lock="loading" :model="postForm" :rules="rules" class="form-container">
      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.state">
        <el-button v-if="!postForm.id" style="margin-left: 10px;" type="success" @click="submitForm">
          确认创建
        </el-button>
        <el-button v-if="postForm.id && postForm.deleted != 1" style="margin-left: 10px;" type="success" @click="submitForm">
          确认修改
        </el-button>
        <el-button style="margin-left: 10px;" type="info" @click="back">
          返回
        </el-button>
      </sticky>

      <div class="createPost-main-container" v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
        <el-row>
          <el-col :span="24">
            <div class="postInfo-container">
              <el-row v-if="postForm.id">
                <!-- <el-col :span="5">
                  <el-form-item label-width="80px" label="最近操作:" class="postInfo-container-item">
                    <label> {{ postForm.updateUserName }} </label>
                  </el-form-item>
                </el-col> -->

                <el-col :span="8">
                  <el-form-item label-width="80px" label="发布时间:" class="postInfo-container-item">
                    <label> {{ parseTime(postForm.addTime) }} </label>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label-width="80px" label="更新时间:" class="postInfo-container-item">
                    <label> {{ parseTime(postForm.updateTime) }} </label>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <el-row>
           <el-col :span="12">
            <el-form-item style="margin-bottom: 30px;" label-width="80px" label="单词">
              <el-input v-model="postForm.name" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item style="margin-bottom: 30px;" label-width="80px" label="拆分">
              <el-input v-model="postForm.disassembly" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 30px;" label-width="80px" label="简单释义">
              <el-input v-model="postForm.simplePh" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item style="margin-bottom: 30px;" label-width="80px" label="全面释义">
              <el-input v-model="postForm.completePh" type="textarea" :autosize="{ minRows: 1 }" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item  label-width="80px" label="单词例句:">
          <!-- <el-button type="success" @click="getMoreExSentence">
            {{ postForm.sentenceList.length == 0? '点击查询单词例句': '点击查看更多未关联例句'}}
          </el-button> -->
          <el-button type="success" @click="createSentence">
            {{ '新增例句'}}
          </el-button>
        </el-form-item>

        <div v-for="(item, index) in postForm.sentenceList" :key="index" style="margin:0;padding:5px;border: 1.5px solid #909399;border-radius: 10px;margin-bottom: 12px;">
          <el-row>
            <el-col :span="2" style="margin-bottom: 5px;">
              <el-form-item label-width="55px" label="启用:" style="margin-bottom: 0px">
                <el-switch
                  v-model="item.enabled"
                  active-color="#13ce66"
                  inactive-color="#909399">
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="2" style="margin-bottom: 5px;">
              <el-form-item label-width="55px" label="序号:" style="margin-bottom: 0px">
                <span>{{index+1}}</span>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="3" style="margin-bottom: 5px">
              <el-form-item label-width="55px" label="分类:" style="margin-bottom: 0px">
                <span>{{item.subCat}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="3" style="margin-bottom: 5px">
              <el-form-item label-width="55px" label="年份:" style="margin-bottom: 0px">
                <span>{{item.subYear}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="3" style="margin-bottom: 5px">
              <el-form-item label-width="55px" label="题型:" style="margin-bottom: 0px">
                <span>{{item.subType}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="2" style="margin-bottom: 5px">
              <el-form-item label-width="55px" label="序号:" style="margin-bottom: 0px">
                <span>{{item.subSort}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="2" style="margin-bottom: 5px">
              <el-form-item label-width="55px" label="段落:" style="margin-bottom: 0px">
                <span>{{item.pSort}}</span>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item label-width="55px" label="句子:" style="margin-bottom: 0px;">
                <span>{{item.sort}}</span>
              </el-form-item>
            </el-col> -->
            <el-col :span="3">
              <!-- <i @click="addItem(item, index)" class="el-icon-circle-plus-outline" style="margin-left: 10px;font-size: 26px;line-height: 30px;cursor:pointer;"></i> -->
              <i @click="removeItem(item, index)" title="移除该例句" class="el-icon-delete" style="margin-left: 5px;font-size: 26px;line-height: 30px;cursor:pointer;"></i>
              <i @click="topItem(item, index)" title="置顶该例句" class="el-icon-upload2" style="margin-left: 5px;font-size: 26px;line-height: 30px;cursor:pointer;"></i>
              <!-- <i @click="goEdit(item.subId)" title="去编辑" class="el-icon-edit-outline" style="margin-left: 5px;font-size: 26px;line-height: 30px;cursor:pointer;"></i> -->
            </el-col>
            <el-col :span="8">
            <el-form-item label="图片" style="width:100%" prop="img">
              <el-upload
                class="avatar-uploader"
                action="https://up-z1.qiniup.com"
                :data="uploadDataObj"
                :show-file-list="false"
                :on-success="(res, file) => handleUploadSuccess(res, file, item)"
                :before-upload="beforeUpload"
              >
                <i class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-row>
                <el-col :span="21" style="margin-bottom: 5px">
                  <el-form-item label-width="55px" style="margin-bottom: 2px" label="句子:">
                    <el-input :ref="'sentenceContent-' + index" v-model="item.content" type="textarea" :autosize="{ minRows: 1 }" />
                  </el-form-item>
                </el-col>
                <el-col :span="3" style="margin-bottom: 5px">
                  <i class='el-icon-s-open' @click="markSentenceContent(item, index)" style="font-size: 26px;line-height: 30px;cursor:pointer;margin-left: 5px;"></i>
                  <i class='el-icon-error' @click="clearMarkSentenceContent(item, index)" style="font-size: 26px;line-height: 30px;cursor:pointer;margin-left: 5px;"></i>
                </el-col>
              </el-row>
              <el-form-item label-width="55px" style="margin-bottom: 2px" label="样例:">
                <p style="line-height:20px;padding-left: 15px;margin-top:8px" v-html="item.contentHtm || item.content"></p>
              </el-form-item>
              <el-row>
                <el-col :span="21" style="margin-bottom: 5px">
                  <el-form-item label-width="55px" style="margin-bottom: 2px" label="释义:">
                    <el-input :ref="'sentencePh-' + index" v-model="item.ph" type="textarea" :autosize="{ minRows: 1 }" @input="sentencePhChangeHandler(item, index)" />
                  </el-form-item>
                </el-col>
                <el-col :span="3" style="margin-bottom: 5px">
                  <i class='el-icon-s-open' @click="markSentencePh(item, index)" style="font-size: 26px;line-height: 30px;cursor:pointer;margin-left: 5px;"></i>
                  <i class='el-icon-error' @click="clearMarkSentencePh(item, index)" style="font-size: 26px;line-height: 30px;cursor:pointer;margin-left: 5px;"></i>
                </el-col>
              </el-row>
              <el-form-item label-width="55px" style="margin-bottom: 2px" label="样例:">
                <p style="line-height:20px;padding-left: 15px;margin-top:8px" v-html="item.phHtm || item.ph"></p>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-row>
                <el-col :span="4" style="margin-bottom: 5px">
                  <img v-if="item.img" :src="item.img" style="width:100px;height:auto">
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          
        </div>
        <div v-if="loading" style="height: 32px;margin:0;padding:5px;border: 1.5px solid #909399;border-radius: 10px;margin-bottom: 12px;line-height: 16px;text-align: center;">
          加载中，请稍后。。。
        </div>

      </div>
    </el-form>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky' // 粘性header组件
import { getWord } from '@/api/word/word'
import { getMoreExSentence, saveOrUpdate, findExSentence } from '@/api/word/sentence'
import { attchUpload } from '@/api/qiniu'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import infiniteScroll from 'vue-infinite-scroll'
import { getUploadToken } from "@/api/tool/qiniu";


const defaultForm = {
  title: '',
  intro: '',
  content: '',
  source: '小白考研',
  publishTime: undefined,
  imgs: [],
  _imgs: [],
  id: undefined,
  type: 1,
  enabled: true,
  sentenceList: []
}

export default {
  name: '单词例句',
  components: { Sticky, Treeselect },
  directives: {infiniteScroll},
  data() {
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
      },
      tempRoute: {},
      dialogImageUrl: '',
      dialogVisible: false,
      uploadDataObj: {},
      imgs: [],
      textMap: {
        update: '编辑',
        create: '新增'
      },
      typeOptions: [ { value: 1, label: '阅读' }, { value: 2, label: '新题型' }, { value: 3, label: '翻译' }, { value: 4, label: '完型' } ],
      catOptions: [{ value: 1, label: '英语一' }, { value: 2, label: '英语二' }],
      defaultSen: {'content': '', 'sort': '', 'pSort': '', 'ph': ''},
      separator: ['$#', '#$'],
      exSenMoreOffset: 0,
      exSenOffset: 0,
      busy: false,
      uploadDataObj: {}
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.detail ? this.postForm.detail.length : 0
    },
    lang() {
      return this.$store.getters.language
    }
  },
  created() {
    this.fetchData(this.$route.params.id)
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    fetchData(id) {
      this.loading = true
      getWord(id).then(response => {
        this.loading = false
        var data = response.data
        data.sentenceList = []
        this.postForm = Object.assign({}, data)
        this.findExSentence(id);
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    findExSentence(id) {
      if(!id) {
        return
      }
      this.busy = true
      this.loading = true
      findExSentence({id: id, offset: this.exSenOffset}).then(res => {
        var list = res.data
        for(var i in list) {
          this.postForm.sentenceList.push(this.buildSentenceAttr(list[i]))
        }
        this.exSenOffset += list.length
        this.busy = false
        this.loading = false
        if(list.length == 0 || this.postForm.exSenNum === this.postForm.sentenceList) {
          this.busy = true
        }
      }).catch(err => {
        this.busy = false
        this.loading = false
        return this.$message.error('例句加载错误，请联系管理员')
      })
    },
    loadMore() {
      // this.findExSentence(this.postForm.id)
    },
    createSentence() {
      this.postForm.sentenceList.push(this.buildSentenceAttr({sps: '', pps: '', content: '', ph: ''}))
    },
    getMoreExSentence() {
      if(this.postForm.sentenceList && this.postForm.sentenceList.length > 0) {
        this.$confirm('是否查找更多例句', '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.buildMoreExSentence()
        }).catch(()=>{})
      } else {
        this.buildMoreExSentence()
      }
    },
    buildMoreExSentence(){
      this.loading = true
      getMoreExSentence({name: this.postForm.name, offset: this.exSenMoreOffset}).then(res => {
        this.loading = false
        var list = res.data
        if(list.length === 0) {
          return this.$message.error('未找到例句')
        }
        this.exSenMoreOffset += list.length
        A: for(var i in list) {
          const d = list[i]
          // 去重
          if(this.postForm.sentenceList && this.postForm.sentenceList.length > 0) {
            B: for(var j in this.postForm.sentenceList) {
              if(this.postForm.sentenceList[j].id === d.id) {
                continue A
              }
            }
          }
          this.postForm.sentenceList.push(this.buildSentenceAttr(d))
        }
        return this.$message.success('例句查找成功')
      }).catch(err => {
        this.loading = false
        return this.$message.error('解析错误，请联系管理员')
      })
    },
    buildSentenceAttr(d) {
      this.typeOptions.forEach(t => {
        if(d.subType === t.value) {
          d.subType = t.label
        }
      })
      this.catOptions.forEach(t => {
        if(d.subCat === t.value) {
          d.subCat = t.label
        }
      })
      d.contentHtm = this.replaceSeparatorToRedFont(d.content)
      d.phHtm = this.replaceSeparatorToRedFont(d.ph)
      d.img = d.img || ''
      return d
    },
    addItem(item, idx){
      var row = Object.assign({}, this.defaultSen)
      row.sort = item.sort
      row.pSort = item.pSort
      this.postForm.sentenceList.splice(idx+1, 0, row)
    },
    removeItem(item, idx) {
      this.postForm.sentenceList.splice(idx, 1)
      this.postForm.removeIds = this.postForm.removeIds || []
      this.postForm.removeIds.push(item.id)
    },
    topItem(item, idx) {
      this.postForm.sentenceList.splice(idx, 1)
      this.postForm.sentenceList.splice(0, 0, item)
      // this.addItem(item, 0)
    },
    // 前往真题编辑
    goEdit(subId) {
      this.$router.push({ path: '/subject/edit/' + subId })
    },
    // 句子标红
    markSentenceContent(item, index) {
      console.log('blurSentencceContent')
      var target = this.$refs['sentenceContent-' + index][0].$el.children[0]
      var start = target.selectionStart
      var end = target.selectionEnd
      if(start === end) {
        return this.$message.error('请选择需要标红的内容')
      }
      item.content = item.content.substring(0, start) + this.separator[0] + item.content.substring(start, end) + this.separator[1] + item.content.substring(end, item.content.length)
      item.contentHtm = this.replaceSeparatorToRedFont(item.content)
      console.log(item.contentHtm)
    },
    // 取消句子标红
    clearMarkSentenceContent (item, index){
      var target = this.$refs['sentenceContent-' + index][0].$el.children[0]
      item.content = item.content.replaceAll('$#', '').replaceAll('#$', '')
      item.contentHtm = item.content
      // var start = target.selectionStart
      // var end = target.selectionEnd
      // if(start === end || start < 2 || item.content.substring(start, start-2) !== this.separator[0] || item.content.substring(end, end+2) !== this.separator[1]) {
      //   return this.$message.error('请选择需要取消标红的内容，必须是' + this.separator[0] + '和' + this.separator[1] + '包含的内容')
      // }
      // item.content = item.content.substring(0, start-2) + item.content.substring(start, end) + item.content.substring(end+2, item.content.length)
      // item.contentHtm = this.replaceSeparatorToRedFont(item.content)
    },
    // 标红译文
    markSentencePh(item, index) {
      var target = this.$refs['sentencePh-' + index][0].$el.children[0]
      var start = target.selectionStart
      var end = target.selectionEnd
      if(start === end) {
        return this.$message.error('请选择需要标红的内容')
      }
      item.ph = item.ph.substring(0, start) + this.separator[0] + item.ph.substring(start, end) + this.separator[1] + item.ph.substring(end, item.ph.length)
      item.phHtm = this.replaceSeparatorToRedFont(item.ph)
      console.log(item.phHtm)
    },
    // 取消译文标红
    clearMarkSentencePh (item, index){
      var target = this.$refs['sentencePh-' + index][0].$el.children[0]
      // var start = target.selectionStart
      // var end = target.selectionEnd
      // if(start === end || start < 2 || item.ph.substring(start, start-2) !== this.separator[0] || item.ph.substring(end, end+2) !== this.separator[1]) {
      //   return this.$message.error('请选择需要取消标红的内容，必须是' + this.separator[0] + '和' + this.separator[1] + '包含的内容')
      // }
      // item.ph = item.ph.substring(0, start-2) + item.ph.substring(start, end) + item.ph.substring(end+2, item.ph.length)
      // item.phHtm = this.replaceSeparatorToRedFont(item.ph)
      item.ph = item.ph.replaceAll('$#', '').replaceAll('#$', '')
      item.phHtm = item.ph
    },
    sentencePhChangeHandler(item, index) {
      item.phHtm = this.replaceSeparatorToRedFont(item.ph)
    },
    replaceSeparatorToRedFont(str) {
      if(!str) {
        return str
      }
      var pre = new RegExp('\\' + this.separator[0].split('')[0] + '\\' + this.separator[0].split('')[1], "g");
      var suf = new RegExp('\\' + this.separator[1].split('')[0] + '\\' + this.separator[1].split('')[1], "g");
      return str.replace(pre, '<font color="red">').replace(suf, '</font>')
    },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          const data = Object.assign({}, this.postForm)
          // 获取原始释义，即剔除分隔符
          var sentenceList = []
          data.sentenceList.forEach(s => {
            if(s.ph) {
              var pre = new RegExp('\\' + this.separator[0].split('')[0] + '\\' + this.separator[0].split('')[1], "g");
              var suf = new RegExp('\\' + this.separator[1].split('')[0] + '\\' + this.separator[1].split('')[1], "g");
              s.phRaw = s.ph.replace(pre, '').replace(suf, '')
            }
            sentenceList.push(s)
          })
          data.sentenceList = sentenceList
          // 提交
          saveOrUpdate(data).then(response => {
            this.loading = false
            this.$message.success('操作成功')
            // 重置
            this.postForm.removeIds = []
          }).catch(e => {
            this.loading = false
            if (e === 'invalid_parameters') {
              this.$message.error('错了哦，请填写完整信息')
            } else {
              this.$message.error(e || '提交失败，请联系管理员')
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG|PNG 格式!')
        return false
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
        return false
      }
      const _self = this
      return new Promise((resolve, reject) => {
        getUploadToken().then(response => {
          console.log(response.data)
          _self._data.uploadDataObj.token = response.data.token
          _self._data.uploadDataObj.key = 'word/sentence/' + this.getNowFormatDate() + '/' + response.data.key
          _self._data.uploadDataObj.domain = response.data.domain
          resolve(true)
        }).catch(err => {
          console.log(err)
          reject(false)
        })
      })
    },
    handleUploadSuccess(res, file, item) {
      item.img = this.uploadDataObj.domain +'/'+ res.key
    },
    back() {
      this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1)
      this.$router.push(this.$store.state.tagsView.visitedViews[this.$store.state.tagsView.visitedViews.length-1].path)
    }
  }
}
</script>

<style lang="scss" scoped>
.createPost-container {
  position: relative;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;
    .postInfo-container {
      position: relative;
      margin-bottom: 10px;
      .postInfo-container-item {
        float: left;
      }
    }
  }
  .word-counter {
    width: 40px;
    position: absolute;
    right: -10px;
    top: 0px;
  }
}
</style>
